<?php
namespace backend\component;


class ResultEasyUIFormat
{
    private $total = 0;

    private $rows = [];



    /**
     * 后台标准数据格式化
     * @param $table
     */
    public static function tableFormat($table) {
        $obj = new self();
        if (!$table || !isset($table['models'])) {
            return $obj;
        }
        $result = [];
        foreach ($table['models'] as $v) {
            $attributes = $v->getAttributes();
            //如果mongodb 中id 则转换成string
            if (isset($attributes["_id"])){
                $attributes["_id"] = (string)$v->_id;
            }
            foreach ($v->ui as $kk=>$vv) {
                if ($kk == 'checked') {
                    $attributes[$kk] = $vv;
                }
                else {
                    $attributes['ui_'.$kk] = $vv;
                }
            }
            $result[] = $attributes;
        }
        $obj->rows = $result;
        $obj->total = $table['pages']->totalCount;
        return $obj;
    }

    /*
     * 转成JSON
     */
    public function asJson() {
        return json_encode($this->asArray());
    }

    /**
     * 返回数组
     * @return array
     */
    public function asArray() {
        return ['total'=>$this->total,'rows'=>$this->rows];
    }
}